﻿/***************************************************************
* File    : EngineeringRecord.cs
* Author  : Kyle Burgess
*
* Description:
*   Module used while building the system. Testing purposes only
*
* History :
***************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace RLGDashboard
{
    class EngineeringRecord
    {
        private string fileName;
        private StreamWriter fileHandle;
        private InQueue transmissionQueue;
        private Thread recordingThread;
        private bool recording;

        public EngineeringRecord()
        {
            DateTime currentTime = DateTime.Now;
            fileName = currentTime.Year + "-" + currentTime.Month + "-" + currentTime.Day + "_" + currentTime.Hour + '.' + currentTime.Minute;
            fileHandle = new StreamWriter(fileName + ".txt");
        }

        public void startRecording(ref InQueue transmissionQueue)
        {
            this.transmissionQueue = transmissionQueue;
            recording = true;
            recordingThread = new Thread(new ThreadStart(record));
            recordingThread.Start();
        }

        public void record()
        {
            EventWaitHandle waitHandle = new AutoResetEvent(false);

            while (recording)
            {
                if (transmissionQueue.CurrentQueueCount != 0)
                {
                    process(transmissionQueue.readFromQueue());
                }
                else
                {
                    waitHandle.WaitOne(10);
                }
            }
        }

        public void stopRecording()
        {
            recording = false;

            while (recordingThread.IsAlive) ;

            fileHandle.Close();
        }

        public void process(BluetoothTransmission transmission)
        {
            fileHandle.WriteLine("NEW");
            fileHandle.WriteLine(transmission.timestamp);
            fileHandle.WriteLine(transmission.messageID);
            fileHandle.WriteLine(transmission.sensors[0]);
            fileHandle.WriteLine(transmission.sensors[1]);
            fileHandle.WriteLine(transmission.sensors[2]);
            fileHandle.WriteLine(transmission.sensors[3]);
            fileHandle.WriteLine("END");
        }
    }
}
